package com.jet.rtdb.socket.client.mina;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jet.rtdb.common.utils.MessageConstant;
import com.jet.rtdb.pojo.QueryHistoryDataList;
import com.jet.rtdb.pojo.QueryLastDataList;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * @Author: zhangkaifeng.
 * @CreateTime: 2017/8/23 11:42
 * @Description:
 */


public class RtdbProtocolDecoder extends CumulativeProtocolDecoder {
    @Override
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        IoBuffer buffer = IoBuffer.allocate(1024).setAutoExpand(true);
        byte type = in.get();
        int length = in.getInt();
        int readLength = in.remaining();
        Integer alreadyReadLength = (Integer) session.getAttribute("alreadyReadLength");
        if(alreadyReadLength != null){
            readLength += alreadyReadLength;
        }
        if (readLength >= length) {
            buffer.put(in);
            byte[] result = new byte[length];
            buffer.flip();
            buffer.get(result);
            String responseMessage = new String(result, "UTF-8");
            GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls();
            Gson gson = gsonbuilder.create();
            switch (type){
                case MessageConstant.GET_POINT_LAST_DATA:
                    QueryLastDataList queryLastDatas = gson.fromJson(responseMessage, QueryLastDataList.class);
                    out.write(queryLastDatas);
                    break;
                case MessageConstant.GET_POINT_HIS_DATA:
                    QueryHistoryDataList queryHistoryDataList = gson.fromJson(responseMessage, QueryHistoryDataList.class);
                    out.write(queryHistoryDataList);
                    break;
            }
            return true;
        } else {
            return false;
        }
    }
}
